<template>
  <div class="dashboard-container">
    <!-- 顶部标题 -->
    <div class="dashboard-header">
      <div class="header-left">
        <h1 class="header-title">数据概览</h1>
        <p class="header-subtitle">实时监控平台数据动态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" size="large" @click="refreshData" :loading="loading" class="refresh-btn">
          <el-icon class="refresh-icon"><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <div class="stat-card user-card">
        <div class="card-background"></div>
        <div class="stat-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ countOfUsers }}</div>
          <div class="stat-title">用户数量</div>
          <div class="stat-trend">
            <span class="trend-up">↑ 12%</span>
            <span class="trend-text">较上月</span>
          </div>
        </div>
      </div>

      <div class="stat-card artist-card">
        <div class="card-background"></div>
        <div class="stat-icon">
          <el-icon><Microphone /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ countOfArtist }}</div>
          <div class="stat-title">歌手数量</div>
          <div class="stat-trend">
            <span class="trend-up">↑ 8%</span>
            <span class="trend-text">较上月</span>
          </div>
        </div>
      </div>

      <div class="stat-card song-card">
        <div class="card-background"></div>
        <div class="stat-icon">
          <el-icon><VideoPlay /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ countOfSong }}</div>
          <div class="stat-title">歌曲数量</div>
          <div class="stat-trend">
            <span class="trend-up">↑ 15%</span>
            <span class="trend-text">较上月</span>
          </div>
        </div>
      </div>

      <div class="stat-card playlist-card">
        <div class="card-background"></div>
        <div class="stat-icon">
          <el-icon><List /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ countOfPlayList }}</div>
          <div class="stat-title">歌单数量</div>
          <div class="stat-trend">
            <span class="trend-up">↑ 5%</span>
            <span class="trend-text">较上月</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <div class="chart-section">
        <div class="chart-header">
          <h3 class="chart-title">歌曲类型分布</h3>
          <div class="chart-actions">
            <el-tag type="info" size="small">实时</el-tag>
          </div>
        </div>
        <div class="chart-container">
          <div ref="songTypeChart" class="chart"></div>
        </div>
      </div>


      <div class="chart-section">
        <div class="chart-header">
          <h3 class="chart-title">歌手性别比例</h3>
          <div class="chart-actions">
            <el-tag type="info" size="small">实时</el-tag>
          </div>
        </div>
        <div class="chart-container">
          <div ref="artistGenderChart" class="chart"></div>
        </div>
      </div>

      <div class="chart-section">
        <div class="chart-header">
          <h3 class="chart-title">歌手地区分布</h3>
          <div class="chart-actions">
            <el-tag type="info" size="small">实时</el-tag>
          </div>
        </div>
        <div class="chart-container">
          <div ref="artistCountryChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 底部版权信息 -->
    <div class="footer">
      <div class="footer-content">
        <p>Copyright © 2024-2025 VibeMusic Admin</p>
        <div class="footer-links">
          <span>版本 v1.0.0</span>
          <el-divider direction="vertical" />
          <span>最后更新: {{ currentTime }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, onUnmounted } from 'vue'
import http from "@/request/http.js";
import * as echarts from 'echarts';
import { Refresh, User, Microphone, VideoPlay, List } from '@element-plus/icons-vue'

// 统计数据
const countOfSong = ref(0);
const countOfArtist = ref(0);
const countOfPlayList = ref(0);
const countOfUsers = ref(0);

// 图表实例引用
const songTypeChart = ref(null);
const artistGenderChart = ref(null);
const artistCountryChart = ref(null);

// 图表实例
let songTypeChartInstance = null;
let artistGenderChartInstance = null;
let artistCountryChartInstance = null;

// 加载状态
const loading = ref(false);
const currentTime = ref(new Date().toLocaleDateString());

// 获取所有统计数据
const fetchAllStats = async () => {
  loading.value = true;
  try {
    const [songRes, artistRes, playlistRes, userRes] = await Promise.all([
      http.get("admin/getAllSongsCount"),
      http.get("admin/getCountOfArtist"),
      http.get("admin/getCountOfPlayList"),
      http.get("admin/getCountOfUser")
    ]);

    countOfSong.value = songRes?.data || 0;
    countOfArtist.value = artistRes?.data || 0;
    countOfPlayList.value = playlistRes?.data || 0;
    countOfUsers.value = userRes?.data || 0;
  } catch (error) {
    console.error('获取统计数据失败:', error);
  } finally {
    loading.value = false;
  }
}

// 获取图表数据 - 歌曲类型
const fetchSongTypeData = async () => {
  try {
    const response = await http.get("admin/song-type-stats");
    const rowData = response?.data || [];

    // 按数量降序排序
    const sortedData = rowData
        .filter(item => item.songStyle !== null)
        .sort((a, b) => b.styleCount - a.styleCount);

    // 取前5个，其他的合并为"其他"
    const top6 = sortedData.slice(0, 5);
    const others = sortedData.slice(5);

    // 计算其他类型的总数
    const otherTotal = others.reduce((sum, item) => sum + item.styleCount, 0);

    const chartData = top6.map(item => ({
      name: item.songStyle,
      value: item.styleCount
    }));

    // 如果有其他类型，添加到图表数据中
    if (otherTotal > 0) {
      chartData.push({
        name: '其他',
        value: otherTotal
      });
    }

    return chartData;
  } catch (error) {
    console.error('获取歌曲类型数据失败:', error);
    return [
      {value: 35, name: '流行'},
      {value: 25, name: '摇滚'},
      {value: 15, name: '电子'},
      {value: 10, name: '古典'},
      {value: 8, name: '爵士'},
      {value: 7, name: '民谣'}
    ];
  }
}

// 获取图表数据 - 歌手性别
const fetchArtistGenderData = async () => {
  try {
    const response = await http.get("admin/artist-gender-stats");
    const rawData = response?.data || [];

    const chartData = rawData.map(item => {
      let genderName = '';
      switch(item.artistGender) {
        case '0':
          genderName = '乐队';
          break;
        case '1':
          genderName = '男';
          break;
        case '2':
          genderName = '女';
          break;
        case null:
          genderName = '未知';
          break;
        default:
          genderName = '其他';
      }

      return {
        name: genderName,
        value: item.artistCount
      };
    });

    return chartData;
  } catch (error) {
    console.error('获取歌手性别数据失败:', error);
    return [
      {name: '乐队', value: 9},
      {name: '男', value: 66},
      {name: '女', value: 26},
      {name: '未知', value: 22}
    ];
  }
}

// 获取图表数据 - 歌手地区分布
const fetchArtistCountryData = async () => {
  try {
    const response = await http.get("admin/artist-country-stats");
    const rawData = response?.data || [];

    const processedData = rawData.map(item => ({
      name: item.artistAreaName || '未知',
      count: item.areaCount
    })).sort((a, b) => b.count - a.count);

    const topCountries = processedData.slice(0, 10);
    const otherCountries = processedData.slice(10);

    const otherCount = otherCountries.reduce((sum, item) => sum + item.count, 0);

    const countries = topCountries.map(item => item.name);
    const counts = topCountries.map(item => item.count);

    if (otherCount > 0) {
      countries.push('其他');
      counts.push(otherCount);
    }

    return {
      countries: countries,
      counts: counts
    };

  } catch (error) {
    console.error('获取歌手地区数据失败:', error);
    return {
      countries: ['中国', '未知', '日本', '法国', '德国', '加拿大', '挪威', '奥地利', '其他'],
      counts: [45, 13, 5, 3, 3, 2, 2, 2, 10]
    };
  }
}

// 安全的图表初始化函数
const safeInitChart = async (chartRef, initFunction) => {
  await nextTick();

  if (!chartRef.value) {
    console.warn('图表容器未找到');
    return;
  }

  // 检查容器尺寸
  if (chartRef.value.clientWidth === 0 || chartRef.value.clientHeight === 0) {
    console.warn('图表容器尺寸为0，延迟初始化');
    setTimeout(() => initFunction(), 100);
    return;
  }

  await initFunction();
}

// 初始化歌曲类型饼图
const initSongTypeChart = async () => {
  if (!songTypeChart.value) return;

  songTypeChartInstance?.dispose();

  const chartData = await fetchSongTypeData();

  try {
    songTypeChartInstance = echarts.init(songTypeChart.value);
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}首 ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#e4e7ed',
        textStyle: {
          color: '#303133'
        }
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'center',
        textStyle: {
          color: '#606266'
        }
      },
      series: [
        {
          name: '歌曲类型',
          type: 'pie',
          radius: ['45%', '70%'],
          center: ['60%', '50%'],
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {d}%',
            color: '#606266'
          },
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 3
          }
        }
      ]
    };
    songTypeChartInstance.setOption(option);
  } catch (error) {
    console.error('初始化歌曲类型图表失败:', error);
  }
}

// 初始化歌手性别比例饼图
const initArtistGenderChart = async () => {
  if (!artistGenderChart.value) return;

  artistGenderChartInstance?.dispose();

  const chartData = await fetchArtistGenderData();

  try {
    artistGenderChartInstance = echarts.init(artistGenderChart.value);
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}人 ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#e4e7ed',
        textStyle: {
          color: '#303133'
        }
      },
      series: [
        {
          name: '性别比例',
          type: 'pie',
          radius: '65%',
          center: ['50%', '50%'],
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {d}%',
            color: '#606266'
          },
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 3
          }
        }
      ]
    };
    artistGenderChartInstance.setOption(option);
  } catch (error) {
    console.error('初始化歌手性别图表失败:', error);
  }
}

// 初始化歌手地区分布柱状图
const initArtistCountryChart = async () => {
  if (!artistCountryChart.value) return;

  artistCountryChartInstance?.dispose();

  const chartData = await fetchArtistCountryData();

  try {
    artistCountryChartInstance = echarts.init(artistCountryChart.value);
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c}人',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#e4e7ed',
        textStyle: {
          color: '#303133'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '12%',
        top: '8%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.countries,
        axisLabel: {
          rotate: 45,
          interval: 0,
          color: '#606266'
        },
        axisLine: {
          lineStyle: {
            color: '#dcdfe6'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '歌手数量',
        nameTextStyle: {
          color: '#909399'
        },
        axisLabel: {
          color: '#606266'
        },
        axisLine: {
          lineStyle: {
            color: '#dcdfe6'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#f0f2f5',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '歌手数量',
          data: chartData.counts,
          type: 'bar',
          barWidth: '55%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: '#36cfc9'},
              {offset: 0.5, color: '#13c2c2'},
              {offset: 1, color: '#08979c'}
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
            color: '#08979c',
            fontWeight: 'bold'
          }
        }
      ]
    };
    artistCountryChartInstance.setOption(option);
  } catch (error) {
    console.error('初始化歌手地区图表失败:', error);
  }
}

// 初始化所有图表
const initAllCharts = async () => {
  await Promise.all([
    safeInitChart(songTypeChart, initSongTypeChart),
    safeInitChart(artistGenderChart, initArtistGenderChart),
    safeInitChart(artistCountryChart, initArtistCountryChart)
  ]);
}

// 刷新数据
const refreshData = async () => {
  await fetchAllStats();
  await initAllCharts();
  currentTime.value = new Date().toLocaleDateString();
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  songTypeChartInstance?.resize();
  artistGenderChartInstance?.resize();
  artistCountryChartInstance?.resize();
}

// 挂载时获取数据和初始化图表
onMounted(async () => {
  await fetchAllStats();

  // 延迟初始化确保DOM完全渲染
  setTimeout(async () => {
    await initAllCharts();
  }, 500);

  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  songTypeChartInstance?.dispose();
  artistGenderChartInstance?.dispose();
  artistCountryChartInstance?.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  padding: 24px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 32px;
  padding: 0 8px;
}

.header-left {
  flex: 1;
}

.header-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-subtitle {
  margin: 0;
  color: #909399;
  font-size: 16px;
  font-weight: 400;
}

.refresh-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.refresh-icon {
  margin-right: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  position: relative;
  border-radius: 20px;
  padding: 32px 24px;
  color: white;
  overflow: hidden;
  transition: all 0.4s ease;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 16px 40px rgba(0, 0, 0, 0.15);
}

.card-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  border-radius: 20px;
}

.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.artist-card {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.song-card {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.playlist-card {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon {
  position: relative;
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.stat-icon .el-icon {
  font-size: 28px;
}

.stat-content {
  position: relative;
}

.stat-number {
  font-size: 42px;
  font-weight: 800;
  line-height: 1;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 16px;
  font-weight: 600;
  opacity: 0.9;
  margin-bottom: 12px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trend-up {
  background: rgba(255, 255, 255, 0.3);
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  backdrop-filter: blur(10px);
}

.trend-text {
  font-size: 12px;
  opacity: 0.8;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(420px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.chart-section {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.chart-section:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #303133;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-container {
  height: 320px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.footer {
  margin-top: 40px;
  border-top: 1px solid #e4e7ed;
  padding-top: 24px;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.footer-content p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.footer-links {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-title {
    font-size: 28px;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .stat-card {
    padding: 24px 16px;
  }

  .stat-number {
    font-size: 32px;
  }

  .chart-section {
    padding: 20px;
  }

  .chart-container {
    height: 280px;
  }

  .footer-content {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }

  .chart-container {
    height: 250px;
  }

  .header-title {
    font-size: 24px;
  }
}
</style>
